import {esri} from "../api/esriAPI";

export class PopupEffect {
  constructor(view) {
    if (!view) {
      throw new Error("没有View对象的传入", view);
    }
    this._view = view;
    this._isLoaded = false;
  }

  _createLayer(view) {
    this._isLoaded =true;
    let box = document.createElement("div");
    box.setAttribute("id", "_popupEffect");
    box.setAttribute("name", "_popupEffect");
    box.style.width = view.width + 'px';
    box.style.height = view.height + 'px';
    box.style.position = "absolute";
    box.style.top = 0;
    box.style.left = 0;
    box.style.overflow = "hidden";
    let popupBox = document.createElement("div");
    popupBox.setAttribute("id", "_popupBox");
    let content = `<svg width="100" height="200" xmlns="http://www.w3.org/2000/svg">
                          <circle class="point" cx="5" cy="195" r="5"/>
                          <!--<path class="line" d="M5 195 C 50 10, 80 10, 100 10" />-->
                          <polyline class="line" points="5,195 5,3 100,3" />
                      </svg>
                      <div class="_content" id="popupBoxContent"></div>`;
    popupBox.innerHTML = content;
    box.appendChild(popupBox);
    let parent = document.getElementsByClassName("esri-view-surface")[0];
    if (parent) {
      parent.appendChild(box);
      this._popupBox = popupBox;
      this._updateMap();
    }
  }

  _addMapEventListeners(view) {
    this._event = esri.watchUtils.when(view, "stationary", this._updateMap.bind(this));
  }
  _updateMap(){
    let view = this._view;
    if(!this._isLoaded){
      return
    }
    let point = new esri.Point({longitude:this._x, latitude:this._y, spatialReference:view.spatialReference});
    var screenP = view.toScreen(point);
    this._popupBox.style.left = screenP.x + "px";
    this._popupBox.style.top = screenP.y + "px";
  }
  open(x,y,html) {
    this._x = x;
    this._y = y;
    if(!this._isLoaded){
      this._createLayer(this._view);
    }else{
      this._popupBox.style.display = "block";
    }
    document.getElementById("popupBoxContent").innerHTML = html;
    this._addMapEventListeners(this._view);

  }
  remove(){
    this._popupBox.style.display = "none";
    this._event.remove();
  }
}
